﻿Imports System.IO
Imports System.Xml
Imports System.Net
Imports System.Web
Imports System.Security.Cryptography.X509Certificates

''' <summary>
''' Global helper methods.
''' </summary>
Public Class utils
    ''' <summary>
    ''' Creates an XmlElement from a stream
    ''' </summary>
    ''' <param name="stream"></param>
    ''' <returns>XmlElement pointing to the root of the XML</returns>
    Public Shared Function CreateXmlNode(ByVal stream As Stream) As XmlElement
        Dim xmlElement As XmlElement
        Dim doc As New XmlDocument()
        Using stream
            doc.Load(stream)
        End Using
        xmlElement = doc.DocumentElement
        Return xmlElement
    End Function

    ''' <summary>
    ''' Returns if a string is empty or null
    ''' </summary>
    ''' <param name="s">the string</param>
    ''' <returns>true if the string is not null and is not empty or just whitespace</returns>
    Public Shared Function IsEmpty(ByVal s As String) As Boolean
        Return s Is Nothing OrElse s.Trim() = String.Empty
    End Function

    ''' <summary>
    ''' Creates an XmlElement from a StreamReader
    ''' </summary>
    ''' <param name="streamReader">the xml input</param>
    ''' <returns>XmlElement pointing to the root of the XML</returns>
    Public Shared Function CreateXmlNode(ByVal streamReader As StreamReader) As XmlElement
        Dim xmlNode As XmlElement
        Dim doc As New XmlDocument()
        Using streamReader
            doc.Load(streamReader)
        End Using
        xmlNode = doc.DocumentElement
        Return xmlNode
    End Function

    Public Const DEFAULT_HTTPPOST_TIMEOUT As Integer = 1000000

    Public Shared Function HttpPost(ByVal url As String, ByVal postData As String) As String
        Return HttpPost(url, postData, DEFAULT_HTTPPOST_TIMEOUT, Nothing)
    End Function

    Public Shared Function HttpPost(ByVal url As String, ByVal postData As String, ByVal timeout As Integer, ByVal x509 As X509Certificate) As String
        Dim objRequest As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
        objRequest.Timeout = timeout
        objRequest.Method = "POST"
        objRequest.ContentLength = postData.Length
        If x509 IsNot Nothing Then
            objRequest.ClientCertificates.Add(x509)
        End If
        Using myWriter As New StreamWriter(objRequest.GetRequestStream())
            myWriter.Write(postData)
        End Using
        Using response As WebResponse = objRequest.GetResponse()
            Using sr As New StreamReader(response.GetResponseStream())
                Return sr.ReadToEnd()
            End Using
        End Using
    End Function
End Class